export default {
	data() {
		return {
			chatSocketTask:'',
			//连接提示
			tin: '',
			//要发送的文本
			text: '',
			//要发送的图片链接
			imgUrl: '',

			//底部工具栏高度
			bottomBoxStyle: 'height: 0rpx;',
			//图片上传提示
			isUpload:'',

			groupId: '',
			groupImg:'',
			userId: '',
			nickname: '',
			headImg: '',
			groupName: '',
			messageList: [],

			startPage: 0,
			endPage: 20,
			//是否刷新信息
			isRefresh: false,
			scrollTop: 0,
			//是否打开群组管理页面
			show: false,
			userList: '',
			adminList: '',
			applyList: '',
			//判断用户是否是管理员
			isAdmin: false,
			//判断用户是否是群主
			isSuperAdmin: false,
			//群主信息
			superAdmin: '',
			
			//是否显示通知页面
			noticeShow:false,
			//通知列表
			noticeList:[],

		}
	},
	onPageScroll(e) {
		//获取滚动条位置
		this.scrollTop = e.scrollTop
	},
	onShow() {
		this.userList = '';
		this.adminList = '';
		this.applyList = '';
		this.show = false;
		this.isAdmin = false;
		this.superAdmin = false;
		
		//获取群组消息列表
		this.getMessageList();
		//开启websocket连接
		this.chatLink();
		//开启上拉刷新
		uni.startPullDownRefresh();
	},
	onLoad(e) {
		//基础信息获取
		this.groupId = e.groupId;
		this.groupName = e.groupName;
		this.groupImg = e.groupImg;
		this.headImg = uni.getStorageSync('headImg');
		this.userId = uni.getStorageSync('userId');
		this.nickname = uni.getStorageSync('nickname');
	},
	onPullDownRefresh() {
		//上拉刷新，获取更早的消息
		this.addRandomData();
		uni.stopPullDownRefresh();
	},
	methods: {
		getMessageList(){
			//请求聊天信息
			this.$request('/Message/queryMessageByGroupId', {
				// 传参参数名：参数值,如果没有，就不需要传
				"groupId": this.groupId,
				"startPage": this.startPage,
				"endPage": this.endPage
			}).then(res => {
				//刚进入页面时获取消息
				if (res.code == 200) {
					var num = 0;
					for (let i in res.data) {
						num++;
					}
					//如果获取不到数据，则直接返回
					if (num == 0) {
						return;
					} else {
						console.log("get_message_ok")
						this.messageList = res.data;
						this.startPage = this.startPage + num;
					}
				}
			})
			//滚动条置底
			this.getScollTop();
		},
		chatLink() {
			var that = this;
			that.chatSocketTask = uni.connectSocket({
				url: that.$ws + '/ChatLink/' + that.groupId + '/' + that.userId,
				success: () => {
					// 返回实例
					return that.chatSocketTask;
				},
			});
			that.chatSocketTask.onOpen(function(res) {
				console.log("chat_link_success")
			});
			that.chatSocketTask.onError(function(res) {
				console.log("chat_link_err")
			});
			that.chatSocketTask.onMessage(function(res) {
				console.log(res.data)
				if (res.data == "200") {

				} else {
					var data = JSON.parse(res.data);
					var m = {
						userId: data.userId,
						nickname: data.nickname,
						headImg: data.headImg,
						messageData: data.messageData,
						createTime: data.createTime
					};
					//插入消息
					that.messageList.push(m);
					that.startPage = that.startPage + 1;
					//滚动条置底
					that.getScollTop();
				}
			});
			console.log("load_ok")
		},
		getScollTop() {
			this.$nextTick(() => {
				//滚动条置底
				setTimeout(() => {
					uni.pageScrollTo({
						scrollTop: 99999999999,
						duration: 0, //app端这个必须设置成0
					})
				}, 50);
			});
		},
		addRandomData() {
			//获取数据并添加进聊天框
			this.$request('/Message/queryMessageByGroupId', {
				// 传参参数名：参数值,如果没有，就不需要传
				"groupId": this.groupId,
				"startPage": this.startPage,
				"endPage": this.endPage
			}).then(res => {
				if (res.code == 200) {
					//避免刚进入页面时触发下拉刷新
					if (!this.isRefresh) {
						this.isRefresh = true;
						return;
					}
					var num = 0;
					for (let i in res.data) {
						num++;
					}
					//如果获取不到数据，则直接返回
					if (num == 0) {
						return;
					} else {
						//向消息数组头部插入获取到的数据
						for (let j in res.data.reverse()) {
							var data = res.data[j];
							var m = {
								userId: data.userId,
								nickname: data.nickname,
								headImg: data.headImg,
								messageData: data.messageData,
								createTime: data.createTime
							};
							this.messageList.unshift(m);
						}
						this.startPage = this.startPage + num;
					}
				}
			})
		},
		//发送消息
		sendMsg() {
			let that = this;
			var msg = that.text + that.imgUrl;
			try {
				if (that.chatSocketTask) {
					that.chatSocketTask.send({
						data: msg
					});
					console.log("send_ok")
					that.text = '';
					that.imgUrl = '';
					//关闭底部工具栏
					that.bottomBoxStyle = 'height: 0rpx;';
				}
			} catch (e) {
				that.chatSocketTask.close({
					success() {
						uni.showToast({
							title: '连接已断开',
							icon: "none"
						});
					}
				});
			}
		},
		//获取群组信息
		groupData() {
			//检查用户是否具有群组管理员权限
			this.$request('/Admin/checkAdminLv', {
				"groupId": this.groupId,
				"userId": this.userId
			}).then(res => {
				//无权限
				if (res.code == 300) {
					this.isAdmin = false;
				}
				//有权限
				if (res.code == 200) {
					if (res.data == 1) {
						//群主权限
						this.isSuperAdmin = true
						this.isAdmin = true;
					}
					if (res.data == 2) {
						//普通管理员权限
						this.isAdmin = true;
					}
				}
			})
			//获取群组群主信息
			this.$request('/Group/querySuperAdminByGroupId', {
				"groupId": this.groupId
			}).then(res => {
				if (res.code == 200) {
					this.superAdmin = res.data;
				}
			})
			//获取群组管理员列表
			this.$request('/Group/queryAdminByGroupId', {
				"groupId": this.groupId
			}).then(res => {
				if (res.code == 200) {
					this.adminList = res.data;
				}
			})
			//获取群组用户列表
			this.$request('/Group/queryUserByGroupId', {
				"groupId": this.groupId
			}).then(res => {
				if (res.code == 200) {
					this.userList = res.data;
				}
			})
			//获取申请加群的用户列表（管理员才可查看）
			this.$request('/Admin/queryUserApplyByGroupId', {
				"groupId": this.groupId
			}).then(res => {
				if (res.code == 200) {
					this.applyList = res.data;
				}
			})
			this.show = true;
		},
		//同意加群
		userJoinGroup(userId) {
			this.$request('/Admin/userJoinGroup', {
				"groupId": this.groupId,
				"userId": userId
			}).then(res => {
				if (res.code == 300) {
					uni.showToast({
						title: '权限不足',
						icon: 'none',
						duration: 2000
					});
				}
				if (res.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: 'none',
						duration: 2000
					});
					this.show = false;
					this.isAdmin = false;
					this.superAdmin = false;
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					});
				}
			})
		},
		//拒绝加群/踢出群
		userExitGroup(userId) {
			this.$request('/Admin/userExitGroup', {
				"groupId": this.groupId,
				"userId": userId
			}).then(res => {
				if (res.code == 300) {
					uni.showToast({
						title: '权限不足',
						icon: 'none',
						duration: 2000
					});
				}
				if (res.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: 'none',
						duration: 2000
					});
					this.show = false;
					this.isAdmin = false;
					this.superAdmin = false;
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						duration: 2000
					});
				}
			})
		},
		//撤销管理员权限
		deleteAdmin(userId) {
			this.$request('/Admin/deleteAdmin', {
				"groupId": this.groupId,
				"userId": userId
			}).then(res => {
				if (res.code == 300) {
					uni.showToast({
						title: '权限不足',
						icon: 'none',
						duration: 2000
					});
				}
				if (res.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: 'none',
						duration: 2000
					});
					this.show = false;
					this.isAdmin = false;
					this.superAdmin = false;
				} else {
					uni.showToast({
						title: '错误',
						icon: 'none',
						duration: 2000
					});
				}
			})
		},
		//新建管理员
		insertAdmin(userId) {
			this.$request('/Admin/insertAdmin', {
				"groupId": this.groupId,
				"userId": userId,
				"lv": 2
			}).then(res => {
				if (res.code == 300) {
					uni.showToast({
						title: '权限不足',
						icon: 'none',
						duration: 2000
					});
				}
				if (res.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: 'none',
						duration: 2000
					});
					this.show = false;
					this.isAdmin = false;
					this.superAdmin = false;
				} else {
					uni.showToast({
						title: '错误',
						icon: 'none',
						duration: 2000
					});
				}
			})
		},
		//群主权限转让
		leaderTransfer(userId) {
			this.$request('/Admin/leaderTransfer', {
				"groupId": this.groupId,
				"userId": userId,
				"optUserId": this.userId
			}).then(res => {
				if (res.code == 300) {
					uni.showToast({
						title: '权限不足',
						icon: 'none',
						duration: 2000
					});
				}
				if (res.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: 'none',
						duration: 2000
					});
					this.show = false;
					this.isAdmin = false;
					this.superAdmin = false;
				} else {
					uni.showToast({
						title: '错误',
						icon: 'none',
						duration: 2000
					});
				}
			})
		},
		//上传照片
		upload() {
			
			//打开底部工具栏
			this.bottomBoxStyle = 'height: 600rpx;';
			this.isUpload = '加载中。。。';
			
			uni.chooseImage({
				//最多上传几张图片
				count: 1,
				success: (chooseImageRes) => {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					const uploadTask = uni.uploadFile({
						url: this.$url + '/Upload/uploadFile',
						filePath: tempFilePaths[0],
						name: 'file',
						formData: {
							'type': 'messageImg'
						},
						success: (uploadFileRes) => {
							var data = JSON.parse(uploadFileRes.data)
							if (data.code == 200) {

								//文本拼接图片
								this.imgUrl = '<img src="' + data.data.url + '" />';
								
								this.isUpload = '';
							} else {
								uni.showToast({
									title: '图片上传出错',
									icon: 'none',
									duration: 2000
								});
								//关闭底部工具栏
								this.bottomBoxStyle = 'height: 0rpx;';
								this.isUpload = '';
							}
						}
					});
				}
			});
		},
		//清除图片
		cleanImg() {
			this.imgUrl = '';
			//关闭底部工具栏
			this.bottomBoxStyle = 'height: 0rpx;';
		},
		//撤回消息
		deleteMessage(e) {
			this.$request('/Message/deleteMessage', {
				"id": e,
				"userId": this.userId,
				"groupId": this.groupId
			}).then(res => {
				if (res.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: 'none',
						duration: 2000
					});
				} else {
					uni.showToast({
						title: '错误',
						icon: 'none',
						duration: 2000
					});
				}
			})
		},
		//@某人
		call(e) {
			this.text = this.text + "@" + e + " ";
		},
		//打开通知页面
		notice(){
			console.log("open notice")
			this.$request('/Notice/queryNoticeByGroupId', {
				// 传参参数名：参数值,如果没有，就不需要传
				"groupId": this.groupId,
				"startPage":0,
				"endPage":100
			}).then(res => {
				if (res.code == 200) {
					this.noticeList = res.data;
					this.noticeShow = true;
					this.show = false;
				}
			})
		},
		//管理员删除通知
		deleteNotice(e){
			this.$request('/Notice/deleteNotice', {
				// 传参参数名：参数值,如果没有，就不需要传
				"noticeId": e
			}).then(res => {
				if (res.code == 200) {
					this.notice();
				}
			})
		},
	}
}
